package com.ruitu.mall_98_seller.mvp.presenter;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.view.View;

import com.ruitu.arad.Arad;
import com.ruitu.arad.api.BaseResult;
import com.ruitu.arad.api.PageModel;
import com.ruitu.arad.base.BasePresenter;
import com.ruitu.arad.util.SHA1;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.mall_98_seller.R;
import com.ruitu.mall_98_seller.dao.bean.Msg;
import com.ruitu.mall_98_seller.mvp.model.MsgModel;
import com.ruitu.mall_98_seller.support.util.MobileUtil;
import com.ruitu.mall_98_seller.ui.home.HomeActivity;
import com.ruitu.mall_98_seller.ui.home.MsgFragment;
import com.ruitu.mall_98_seller.ui.msg.MsgDetailActivity;
import com.ruitu.mall_98_seller.ui.msg.MsgListActivity;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.Config;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.RongToken;
import com.ruitu.router_module.bean.RongUser;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.UUID;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

public class MsgPresenter {

    public static class MsgListP extends BasePresenter<MsgListActivity, MsgModel.MsgListM> {

        public Disposable reqMsgList(String comId, int size, final int page) {
            return m.reqMsgList(comId, size, page)
                    .subscribe(new Consumer<BaseResult<PageModel<Msg>>>() {
                        @Override
                        public void accept(BaseResult<PageModel<Msg>> pageResult) throws Exception {
                            v.hideProgress();
                            if (pageResult.isSuccess()) {
                                v.onReqComplete(1, true, pageResult.getData());
                            } else {
                                ToastUtils.showShortSafe(pageResult.getMsg());
                                v.setEmptyViewVisible(View.VISIBLE);
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            v.hideProgress();
                            throwable.printStackTrace();
                            ToastUtils.showShortSafe("请求异常,请稍后重试");
                            v.setEmptyViewVisible(View.VISIBLE);
                        }
                    });
        }

        public Disposable reqAllReadMsg(String comId) {
            return m.reqAllReadMsg(comId).subscribe(new Consumer<BaseResult>() {
                @Override
                public void accept(BaseResult baseResult) throws Exception {
                    v.hideProgress();
                    if (baseResult.isSuccess()) {
                        v.onReqComplete(2, true, null);
                    } else {

                    }
                    ToastUtils.showShortSafe(baseResult.getMsg());
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    v.hideProgress();
                    throwable.printStackTrace();
                    ToastUtils.showShortSafe("标记全部已读异常,请稍后重试");
                }
            });
        }
    }

    // 消息详情
    public static class MsgDedetialP extends BasePresenter<MsgDetailActivity, MsgModel.MsgDetailM> {

        public Disposable reqMsgDetail(String msgId) {
            return m.reqMsgDetail(msgId).subscribe(new Consumer<BaseResult<Msg>>() {
                @Override
                public void accept(BaseResult<Msg> result) throws Exception {
                    v.hideProgress();
                    if (result.isSuccess()) {
                        v.onReqComplete(1, true, result.getData());
                    } else {
                        ToastUtils.showShortSafe(result.getMsg());
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    v.hideProgress();
                    throwable.printStackTrace();
                    ToastUtils.showShortSafe("获取消息异常,请稍候重试");
                }
            });
        }
    }

    // 消息fragment
    public static class MsgFragP extends BasePresenter<MsgFragment, MsgModel.MsgFragM> {

        // 请求未读消息数量 不需要显示进度条
        public Disposable reqUnReadMsgNum(String comId) {
            return m.reqUnReadMsgNum(comId).subscribe(new Consumer<BaseResult<String>>() {
                @Override
                public void accept(BaseResult<String> result) throws Exception {
                    if (result.isSuccess()) {
                        v.onReqComplete(1, true, result.getData());
                    } else {

                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    throwable.printStackTrace();
                }
            });
        }

        // 请求融云token 连接融云
        public Disposable connectRong() {
            final String appKey = "sfci50a7s3osi";// appKey
            final String uuid = UUID.randomUUID().toString();
            final String nonce = uuid;
            final String timeStamp = System.currentTimeMillis() + "";
            final String signiture = SHA1.encode("PzxRAJWcxTRY" + nonce + timeStamp);// Secret
            final String userId = AppHolder.instance().getUser().getId();
            final String userName = AppHolder.instance().getUser().getCompany().getName();

            String tmpPortrait = Config.BASE_URL + AppHolder.instance().getUser().getCompany().getImageUrl();
            final String portrait = TextUtils.isEmpty(tmpPortrait) ? "..." : tmpPortrait;

            return m.reqRongToken(appKey, nonce, timeStamp, signiture, userId, userName, portrait)
                    .subscribe(new Consumer<RongToken>() {
                        @Override
                        public void accept(RongToken rongToken) throws Exception {
                            String token = rongToken.getToken();// 融云token
                            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                                //Token 错误。可以从下面两点检查 1.Token是否过期,如果过期您需要向AppServer重新请求一个新的Token
                                //2.token 对应的appKey 和工程里设置的appKey 是否一致
                                @Override
                                public void onTokenIncorrect() {
                                    ToastUtils.showShort("融云token错误");
                                }

                                @Override//连接融云成功
                                public void onSuccess(String userid) {
                                    Logg.i("融云连接成功...");
                                    getRongUnReadMsgNum();// 获取未读消息数量
                                    v.onReqComplete(2, true, null);
                                    // 为融云提供用户系统
                                    RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
                                        @Override
                                        public UserInfo getUserInfo(final String rongId) {
//                                        Logg.i("自己的id = " + userId + ",回调id = " + rongId);
                                            m.reqUserInfo(rongId).subscribe(new Consumer<BaseResult<RongUser>>() {
                                                @Override
                                                public void accept(BaseResult<RongUser> userResult) throws Exception {
                                                    RongIM.getInstance().setMessageAttachedUserInfo(true);//是否携带用户信息,true携带,false不携带.
                                                    RongUser u = userResult.getData();
                                                    UserInfo userInfo = new UserInfo(u.getAccountId(), u.getName(), Uri.parse(Config.BASE_URL + u.getHead()));
                                                    RongIM.getInstance().refreshUserInfoCache(userInfo);//刷新需要的用户信息
                                                }
                                            }, new Consumer<Throwable>() {
                                                @Override
                                                public void accept(Throwable throwable) throws Exception {
                                                    throwable.printStackTrace();
                                                }
                                            });
                                            return null;//
                                        }
                                    }, true);

                                    // 收到融云消息的监听
                                    RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
                                        @Override
                                        public boolean onReceived(io.rong.imlib.model.Message message, int i) {
                                            getRongUnReadMsgNum();//收到融云消息,获取未读消息数量
                                            return false;
                                        }
                                    });
                                }

                                @Override//连接融云失败
                                public void onError(RongIMClient.ErrorCode errorCode) {
                                    if (isFirst) {
                                        ToastUtils.showShort("连接融云失败");
                                    }
                                    isFirst = false;
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            connectRong();
                                        }
                                    }, 6000);
                                }
                            });
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            throwable.printStackTrace();
                        }
                    });
        }

        private boolean isFirst = true;
        public int rongMsgNum = 0;// 融云消息数量

        // 获取融云未读消息数量
        public void getRongUnReadMsgNum() {
            RongIMClient.getInstance().getTotalUnreadCount(new RongIMClient.ResultCallback<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    Logg.i("getRongUnReadMsgNum()成功 : " + integer);
                    rongMsgNum = integer;
                    Arad.bus.post(new EventModel(19010251, integer));// 融云消息数量
                    if (CommonUtils.isLogin()) {
                        reqUnReadMsgNum(AppHolder.instance().getUser().getCompany().getId());
                    }
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    Logg.i("getRongUnReadMsgNum()异常 errorCode = " + errorCode);
                    rongMsgNum = 0;
                    Arad.bus.post(new EventModel(19010251, 0));// 融云消息数量
                    // 不管融云未读消息获取成功与否,都要获取系统未读消息数量
                    if (CommonUtils.isLogin()) {
                        reqUnReadMsgNum(AppHolder.instance().getUser().getCompany().getId());
                    }
                }
            });
        }

        // 设置桌面角标消息数量 (暂时设置MIUI 6-10 EMUI)
        public void setBadgeNum(int count, Context context, boolean isMiuiShow) {
            if (MobileUtil.isEMUI()) {
                setEmuiBadge(count, context);
            } else if (MobileUtil.isMIUI()) {
                if (isMiuiShow && count > 0) {
                    setMiuiBadge(count, context);
                }
            } else {
//                Logg.i("暂不支持该机型设置桌面角标！");
            }
        }

        // 小米手机手机发送消息到通知栏并设置角标
        public boolean setMiuiBadge(int count, Context context) {
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            if (notificationManager == null) return false;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // 8.0之后添加角标需要NotificationChannel
                NotificationChannel channel = new NotificationChannel("badge", "badge", NotificationManager.IMPORTANCE_DEFAULT);
                channel.setShowBadge(true);
                notificationManager.createNotificationChannel(channel);
            }
            Intent intent = new Intent(context, HomeActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
            Notification notification = new NotificationCompat.Builder(context, "badge")
                    .setContentTitle("九八商城企业版")
                    .setContentText("您有" + count + "条未读消息")
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.app_icon))
                    .setSmallIcon(R.mipmap.app_icon_round)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setChannelId("badge")
                    .setNumber(count)
                    .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL).build();
            // 小米
            try {
                Field field = notification.getClass().getDeclaredField("extraNotification");
                Object extraNotification = field.get(notification);
                Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
                method.invoke(extraNotification, count);
            } catch (Exception e) {
                e.printStackTrace();
            }
//            notificationManager.notify(new Random().nextInt(99999999) + 1, notification);
            notificationManager.notify(19090699, notification);
            return true;
        }

        // 华为手机设置角标
        public boolean setEmuiBadge(int count, Context context) {
            try {
                String launchClassName = MobileUtil.getLauncherClassName(context);
                if (TextUtils.isEmpty(launchClassName)) {
                    return false;
                }
                Bundle bundle = new Bundle();
                bundle.putString("package", context.getPackageName());
                bundle.putString("class", launchClassName);
                bundle.putInt("badgenumber", count);
                context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, bundle);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }
}
